#include<iostream>
#include<string>
#include<memory>
#include<sstream>
#include<jsoncpp/json/json.h>

bool serialize(const Json::Value& val, std::string& body)
{
    
    std::stringstream ss;
    //先实例化工厂类对象， 再进行派发
    Json::StreamWriterBuilder swb;
    swb.settings_["emitUTF8"] = true; 
    //newStreamWriter的返回值是StreamWriter*
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    int ret = sw->write(val, &ss);
    if(ret != 0)
    {
        std::cout<<"streamWrite write fail!" << std::endl;
        return false;
    }
    body = ss.str();
    return true;
}

bool deserialize(const std::string& body, Json::Value& val)
{
    //实例化工厂类对象
    Json::CharReaderBuilder crb;
    //生产对象
    std::string errs;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    bool ret = cr->parse(body.c_str(), body.c_str()+body.size(), &val, &errs);
    if(!ret){
        std::cout<<"Json deserialize fail! :" << errs << std::endl;
        return ret;
    }
    return ret;
}

int main()
{
    const char* name = "张三";
    const char* sex = "男";
    int age = 20;
    double score[3] = {99.5, 80, 60.5};
    Json::Value val;
    val["姓名"] = name;
    val["性别"] = sex;
    val["年龄"] = age;
    val["分数"].append(score[0]);
    val["分数"].append(score[1]);
    val["分数"].append(score[2]);
    Json::Value fav;
    fav["书籍"] = "挪威的森林";
    fav["游戏"] = "我的世界";
    val["爱好"] = fav;
    std::string body;
    serialize(val, body);
    std::cout<<body<<std::endl;
    return 0;
}